<?php

namespace Addons\OaSystem\Controller;

use Think\ApiBaseController;
include_once "pkcs7Encoder.php";
include_once "errorCode.php";

class ApiController extends ApiBaseController
{
    var $token;
    var $appid;
    public function __construct() {
        parent::__construct ();
        $this->token = get_token();
        $this->appid = get_app_info()['appid'];
    }
    function GetSessionCode() {
        $code = I ( 'code' );
        $appid = I('appid');
        $config = D ( 'Common/Apps' )->getInfoByAppid($this->appid);

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$config['appid']}&secret={$config['secret']}&js_code={$code}&grant_type=authorization_code";
        // openid 用户唯一标识 session_key 会话密钥
        $data = post_data ( $url, [ ] ); // {"session_key":"gHkoobsIWnTYnUj1ZTQKDA==","expires_in":2592000,"openid":"onfcX0fV3mjzsLRK7C15vk_2N86w"}
        if ((isset ( $data ['errcode'] ) && $data ['errcode'] == '40029') || ! isset ( $data ['session_key'] ) || ! isset ( $data ['openid'] )) {
            echo api_return ( 410001, [ ], '获取微信信息失败！' );
        } else {
            session ( 'session_key', $data ['session_key'] );
            get_openid( $data ['openid']);
            $map ['openid'] = $map2 ['a.openid'] = $data ['openid'];
            if (! M ( 'apps_follow' )->where ( $map )->find ()) {
                $uid = M ( 'user' )->add ( [
                    'reg_time' => NOW_TIME
                ] );
                M ( 'apps_follow' )->add ( [
                    'token' => $config ['token'],
                    'openid' => $data ['openid'],
                    'uid' => $uid
                ] );
            } else {
                $re = M ( 'apps_follow as a' )->join ( C ( 'DB_PREFIX' ) . 'user b on a.uid = b.uid' )->where ( $map2 )->find ();

                session ( 'user_info', $re );
                $uid = $re ['uid'];
            }
            // $uid = 1;
            // $this->saveSession ();
            session ( 'mid', $uid );
            /*
             * session('mid',1);
             */

            $return ['PHPSESSID'] = session_id ();
            $return ['openid'] = $data ['openid'];
            $return ['uid'] = $uid;
            echo api_return ( 0, $return );

        }
    }
    private function decrypData($key,$encryptedData,$iv,&$data){

        $aesKey=base64_decode($key);
        $aesIV=base64_decode($iv);
        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj=json_decode( $result);
        if( $dataObj  == NULL )
        {
            return '40002';
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return '40003';
        }
        $data = $result;

        return 0;
    }
    function saveUserInfo() {
        $encryptedData = I ( 'encryptedData' );
        $iv = I ( 'iv' );
        // var_dump(I ( 'encryptedData' ));
        if ($encryptedData != '' && $iv != '') {
            $sessionKey = session ( 'session_key' );
            /*
                vendor ( 'aes.wxBizDataCrypt' );
                $config = get_token_appinfo ();
                $appid = $config ['appid'];
                $pc = new \WXBizDataCrypt ( $appid, $sessionKey );
                $errCode = $pc->decryptData ( $encryptedData, $iv, $data );
            */
            $errCode = $this->decrypData($sessionKey,$encryptedData,$iv,$data);
            if ($errCode == 0) {
                $data = json_decode ( $data, true );
                session ( 'user_info', $data );
                $save = [
                    'nickname' => $data ['nickName'],
                    'sex' => $data ['gender'],
                    'language' => $data ['language'],
                    'city' => $data ['city'],
                    'province' => $data ['province'],
                    'country' => $data ['country'],
                    'headimgurl' => $data ['avatarUrl']
                ];
                isset ( $data ['unionid'] ) && $save ['unionid'] = $data ['unionid'];
                $uid = session ( 'mid' );
                if ($uid > 0) {
                    $res = D ( 'Common/User' )->updateInfo ( $uid, $save );
                    $save ['uid'] = $uid;
                    D ( 'Common/User' )->autoLogin ( $save );
                    echo api_return ( 0, $res );
                    // var_dump($res);
                } else {
                    echo api_return ( 4100025, [ ], '用户ID错误' );
                }
            } else {
                // print($errCode . "\n");
                echo api_return ( $errCode, [ ] );
            }
        } else {
            echo api_return ( 140002, [ ], '缺少用户加密信息' );
        }
    }
    function checkLogin() {
        if ($this->mid > 0)
            echo api_success ( array('data'=>$this->mid));
        else
            echo api_error ( '用户登录消息不存在，请重新登录' );
    }
    public function GetSmsCode() {
        $mobile = I ( 'mobile' );

        $map['mobile'] = $mobile;
        $map['appid'] = get_app_info()['appid'];;
        $userMobile = M('OaUserEmployee')->where($map)->find();
        if ($userMobile == null){
            $res['errcode'] = '46004';
            echo api_return('46004',null,error_msg($res,'电话号码未被登记'));
        }else {
            if(session('verifycode'.$mobile) !== -1){
                if(NOW_TIME - session('verifycode'.$mobile)['time'] < 60) {
                    $res['errcode'] = '46004';
                    echo api_return('46004',null,error_msg($res,'离上次发送的时间还不到1分钟！'));
                }
            }
            $map['time'] = NOW_TIME;
            session('verifycode'.$mobile, $map);
            $res = D( 'sms')->sendSms( $mobile, 'card' );
            $res ['uid'] = $this->mid;
            echo api_return($res['errcode'], null, $res['msg']);
        }
    }
    public function SmsRegister(){
        $mobile = I ( 'mobile');
        $code = I ('code');
        $appid = get_app_info()['appid'];
        $openid =  get_openid();

        $res = D( 'sms')->checkSms( $mobile, $code);
        $res ['uid'] = $this->mid;
        if ($res['errcode'] != 0) {
            echo json ( $res );
        }else{
            $map['mobile'] = $mobile;
            $map['appid'] = $appid;
            $userMobile = M('OaUserEmployee')->where($map)->find();
            if ($userMobile == null){
                $res['errcode'] = '46004';
                echo api_return('46004',null,error_msg($res));
            }else{
                $userMobile['openid'] = $openid;
                $userMobile['update_time'] = date('y-m-d h:i:s', time());;
                $userMobile['userid'] = $this->mid;
                D('OaUserEmployee')->update($userMobile);
                $map2['id'] = $userMobile['emp_id'];
                $empinfo = M('OaEmployee')->where($map2)->find();
                if($empinfo == NULL){
                    echo api_return('46004',null,'员工信息未登记');
                }else{
                    $uid = 0;
                    $save = [
                        'nickname' => $empinfo ['account'],
                        'truename' => $empinfo['name'],
                        'mobile' => $empinfo['mobile'],
                        'status'=>1,
                        'is_init'=>1
                    ];
                    if(empty($empinfo['userid'])){
                        $uid = D('Common/User')->addUser($save);
                        $empinfo['userid'] = $uid;
                        $empinfo['registered'] = true;
                        M('OaEmployee')->where($map2)->save($empinfo);
                    }else{
                        $uid = $empinfo['userid'];
                        D ( 'Common/User' )->updateInfo($uid, $save);
                        echo api_return( 0,$empinfo);
                        return ;
                    }

                    $pwd['password'] = $empinfo['password'];
                    $pwd['login_password'] = $empinfo['password'];
                    $res = D ( 'Common/User' )->forceupdateUserPassword( $uid, $pwd );
                    if ($res === false){
                        echo api_return('46004',null,'注册失败：员工信息未登记');
                        return ;
                    }
                    $manager_map ['uid'] =$uid;
                    $manager_data['copy_right'] = 'OA System';
                    $manager_data['has_public'] = 0;

                    if (M ( 'manager' )->where ( $manager_map )->find ()) {
                        M ( 'manager' )->where ( $manager_map )->save ( $manager_data );
                    } else {
                        $manager_data['uid'] = $uid;
                        M ( 'manager' )->add ($manager_data);
                    }
                    $links_data ['uid'] =  $uid;;
                    $links_data ['mp_id'] = WPID;

                    $links_map['uid'] = $uid;;
                    if (M ( 'apps_link' )->where ( $links_map )->find ()) {
                        M ( 'manager' )->where ( $links_map )->save ( $links_data );
                    }else{
                        M ( 'apps_link' )->add ( $links_data );
                    }
                    echo api_return( 0,$empinfo);
                }
            }
        }
    }

    public function uploadFile() {
        /* 返回标准数据 */
        $return = array (
            'status' => 1,
            'msg' => '上传成功',
            'data' => ''
        );

        /* 调用文件上传组件上传文件 */
        $file_model = D ( 'Home/File' );
        $info = $file_model->upload ( $_FILES, C ( 'DOWNLOAD_UPLOAD' ), C ( 'UPLOAD_LOCAL_CONFIG' ), C ( "UPLOAD_LOCAL_CONFIG" ) ); // TODO:上传到远程服务器

        /* 记录图片信息 */
        if ($info) {
            $return ['status'] = 1;
            $return = array_merge ( $info ['download'], $return );
        } else {
            $return ['status'] = 0;
            $return ['msg'] = $file_model->getError ();
        }
        add_debug_log ( $return, 'upload_return' );
        /* 返回JSON数据 */
        $this->ajaxReturn ( $return );
    }

// 保存小程序的图片
    public function uploadPicture() {
        /* 返回标准数据 */
        $return = array (
            'errcode' => 0,
            'msg' => '上传成功',
            'data' => null
        );

        /* 调用文件上传组件上传文件 */
        $Picture = D ( 'Home/Picture' );
        $pic_driver = C ( 'PICTURE_UPLOAD_DRIVER' );
        $info = $Picture->upload ( $_FILES, C ( 'PICTURE_UPLOAD' ), C ( 'PICTURE_UPLOAD_DRIVER' ), C ( "UPLOAD_{$pic_driver}_CONFIG" ) ); // TODO:上传到远程服务器

        /* 记录图片信息 */
        if ($info) {
            $return ['errcode'] = 0;
            $return['data'] =  $info ['download'];
        } else {
            $return ['errcode'] = '9001010';
            $return ['msg'] = $Picture->getError ();
        }
        add_debug_log ( $return, 'upload_return' );
        /* 返回JSON数据 */
        $this->ajaxReturn ( $return );
    }

    public function GetDepts(){
        if(empty(I('dept_id'))){
            $data = M('OaDept')->select();
            echo api_return(0,$data);
            return;
        }else{
            $map['id'] = I('dept_id');
            $data = M('Oadept')->where($map)->find();
            echo api_return(0,$data);
            return;
        }
    }

    public function GetEmpByOpenid(){
        $map['openid'] = get_openid();
        $map['$appid'] = get_app_info()['appid'];
        $userMobile = M('OaUserEmployee')->where($map)->find();
        if (empty($userMobile)){
            $res['errcode'] = '46004';
            echo api_return('46004',null,error_msg($res));
        }else{
            $map2['id'] = $userMobile['emp_id'];
            $empinfo = M('OaEmployee')->where($map2)->find();
            $empinfo['level'] = M('OaDuty')->where(array('id'=>$empinfo['duty_id']))->getField('level');
            if(empty($empinfo)){
                echo api_return('46004',null,'员工信息未登记');
            }else{
                session ( 'empId', $empinfo['id'] );
                echo api_return( 0,$empinfo);

            }
        }
    }

    public function GetEmpSelfInfo(){
        $map['userid'] = $this->mid;
        $map['$appid'] = get_app_info()['appid'];
        $userMobile = M('OaUserEmployee')->where($map)->find();
        if (empty($userMobile)){
            $res['errcode'] = '46004';
            echo api_return('46004',null,error_msg($res));
        }else{
            $map2['emp_id'] = $userMobile['emp_id'];
            $empinfo = M('OaEmployee')->where($map2)->find();
            if(empty($empinfo)){
                echo api_return('46004',null,'员工信息未登记');
            }else{
                session ( 'empId', $empinfo['id'] );
                echo api_return( 0,$empinfo);

            }
        }
    }

    public function GetEmpBusiness(){
        $res['errcode'] = 0;
        $res['msg'] = 0;
        $res['data'] = null;
        echo json ( $res );
    }

    public function GetEmpApproving(){
        if(empty( I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
        }
        $map['approver'] = I('emp_id');
        $map['status'] = array('neq',1);
        $map['step'] = array('gt',1);
        if(!empty(I('apply_id'))) {
            $map['id'] = I('apply_id');
        }
        if (!empty(I('page'))){
            $p = I('page');
            $data = D('OaApplicationView')->where($map)->order('submit_date desc')->page($p,20)->select();
        }else{
            $data = D('OaApplicationView')->where($map)->order('submit_date desc')->select();
        }

        echo api_return( 0,$data);
    }

    public function EmpClockOn(){
        $emp_id = I('emp_id');
        $location = json_decode(I('location'),true);
        // $wifi = I('wifi');
        $type = I('type');
        $statement = I('statement');

        if (empty($location) && empty($wifi)) {
            $res['errcode'] = '40008';
            echo api_return($res['errcode'],null,error_msg($res));
        }else{
            $map['emp_id'] = $emp_id;
            $map['type'] = $type;
            $map['date'] = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $map['appid'] = $this->appid;
            $data = M('OaEmpAttendance')->where($map)->find();
            if(empty($data)) {
                $data['emp_id'] = $emp_id;
                $data['type'] = $type;
                $data['appid'] = $this->appid;
                $data['date'] = mktime(0,0,0,date('m'),date('d'),date('Y'));
                $data['time'] = NOW_TIME;
		$data['location'] = json_encode($location);
/*
                if(!empty($location)) {
                    $tmp['gps'] = $location;
                    $data['location'] = json_encode($tmp);

                }else if(!empty($wifi)) {
                    $tmp['wifi'] = $wifi;
                    $data['location'] = json_encode($tmp);
                }
*/
                $res = M('OaEmpAttendance')->add($data);
                $data = M('OaEmpAttendance')->where(array('id'=>$res))->find();
            } else {
                if (empty($statement)) {
                    $data['time2nd'] = NOW_TIME;
		    $data['location2nd'] = json_encode($location);
                } else {
                    $data['statement'] = $statement;
                }
/*
                if(!empty($location)) {
                    $tmp['gps'] = $location;
                    $data['location2nd'] = json_encode($tmp);

                }else if(!empty($wifi)) {
                    $tmp['wifi'] = $wifi;
                    $data['location2nd'] = json_encode($tmp);
                }
*/
                M('OaEmpAttendance')->where(array('id'=>$data['id']))->save($data);
            }

            echo api_return(0,$data);
        }
    }

    public function GetEmpAttendence(){
        $map['emp_id'] = I('empid');
        $map['date'] = array('between',array(I('startTime'),I('endTime')));
        $map['appid'] = $this->appid;
        $attendances = M('OaEmpAttendance')->where($map)->select();

        echo api_return(0,$attendances);
    }

    public function ApplyForWorkOverTime(){

        $res['errcode'] = 0;
        $res['msg'] = 0;
        $res['data'] = null;
        echo json ( $res );
    }

    public function GetApplyForWorkOverTime(){
        if(!empty(I('applyer'))){
            $map['applyer'] = I('applyer');
        }
        $map['id'] = I('apply_id');
        $map['type'] = 1;

        $data = M('OaApplication')->where($map)->find();
        echo api_return(0,$data);
    }

    public function UpdateApplyForWorkOverTime(){

        $res['errcode'] = 0;
        $res['errmsg'] = 0;
        $res['data'] = null;
        echo json ( $res );
    }

    public function ApplyForLeave(){

        $res['errcode'] = 0;
        $res['errmsg'] = 0;
        $res['data'] = null;
        echo json ( $res );
    }
    public function GetApplyForLeave(){
        $map['id'] = I('apply_id');
        $map['type'] = 2;
        $data = M('OaApplication')->where($map)->find();
        echo api_return(0,$data);
    }

    public function UpdateApplyForLeave(){

        $res['errcode'] = 0;
        $res['errmsg'] = 0;
        $res['data'] = null;
        echo json ( $res );
    }
    public function GetAdminLvl() {
        $data = M('OaEmpAdminLevel')->select();
        echo api_return( 0,$data);
    }

    public function GetEmployeeFunSettings () {
        if (empty(I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        $data = M('OaEmpset')->where(array('emp_id'=>I('emp_id')))->find();
        if (empty($data)) {
            $data = array('emp_id'=>I('emp_id'));
            $res = M('OaEmpset')->add($data);
            if($res === false) {
                $return['errcode'] = '61451';
                echo api_return($return['errcode'],$res,error_msg($return,'createSetting failed!!'));
                return;
            }
            $data = M('OaEmpset')->where(array('id'=>$res))->find();
        }

        echo api_return(0,$data);
    }

    public function SetEmployeeFunSettings () {
        if (empty(I('data'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        $new_data = json_decode(I('data'),true);
        $data = M('OaEmpset')->where(array('emp_id'=>$new_data['emp_id']))->find();
        if(empty($data)) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return,'can not find this employee!!'));
            return;
        }else{
            $res = M('OaEmpset')->where(array('id'=>$data['id']))->save($new_data);
            if ($res === false) {
                $return['errcode'] = '61451';
                echo api_return($return['errcode'],$res,error_msg($return,'save failed!!'));
                return;
            }else {
                echo api_return(0,null);
            }
        }

    }

    public function UpdateEmpFormId () {
        if ((empty(I('openId'))) || (empty(I('formId'))) || (empty(I('emp_id')))) {
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],$res,error_msg($return));
            return;
        }
        $num = M('OaEmpWxformid')->where(array('emp_id'=>I('emp_id')))->count();
        if ( $num > 50) {
            $formInfo = M('OaEmpWxformid')->where(array('emp_id'=>I('emp_id')))->order('validtime')->page(0,20)->select();
            $formIds = array_column($formInfo, 'id');
            M('OaEmpWxformid')->where(array('in',$formIds))->delete();
        }
        $data['emp_id'] = I('emp_id');
        $data['openid'] = I('openId');
        $data['formid'] = I('formId');
        $data['validtime'] = strtotime("+7 day");
        $ret = M('OaEmpWxformid')->add($data);

        echo api_return(0,$ret);
    }

    public function GetMyRoles () {
        if(empty(I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $data = D('OaUserRoleEmployeeView')->where(array('emp_id'=>I('emp_id')))->select();
        echo api_return(0,$data);
    }

    public function GetMyAssignedRoles () {
        if(empty(I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $data = D('OaUserRoleEmployeeView')->where(array('assigned_by'=>I('emp_id')))->select();
        echo api_return(0,$data);
    }

    public function GetUserRoles () {
        if(empty(I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $roles = D('OaUserRoleView')->where(array('emp_id'=>I('emp_id')))->select();
        $empInfo = D('OaEmployeeDeptView')->where(array('id'=>I('emp_id')))->find();
        $data = array();
        foreach ($roles as $role) {
            if ($role['role_level'] == $empInfo['duty_lvl'] && $role['role_level'] > 11) {
                array_push($data,$role);
            }
        }
        echo api_return(0,$data);
    }

    public function GetMySubEmployees () {
        if(empty(I('emp_id'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $empInfo = D('OaEmployeeDeptView')->where(array('id'=>I('emp_id')))->find();
        $emps = D('OaEmployeeDeptView')->where(array('dept_id'=>$empInfo['dept_id']))->select();
        $data = array();
        foreach ($emps as $emp) {
            if ($emp['duty_lvl'] < $empInfo['duty_lvl']) {
                $roles = M('OaUserRole')->where(array('emp_id'=>$emp['id']))->select();
                $emp['roles'] = $roles;
                array_push($data,$emp);
            }
        }
        echo api_return(0,$data);
    }

    public function UpdateMyEmpowerRole() {
        if(empty(I('data'))){
            $return['errcode'] = '61451';
            echo api_return($return['errcode'],null,error_msg($return));
            return;
        }
        $data = json_decode(I('data'),true);
        // var_dump($data);
        foreach ($data['emps'] as $emp) {
            $map['role_id'] = $data['role_id'];
            $map['emp_id'] = $emp['emp_id'];
            $userRole = M('OaUserRole')->where($map)->find();

            if(empty($userRole)){
                if($emp['empower']) {
                    $tmp['emp_id'] = $emp['emp_id'];
                    $tmp['role_id'] = $data['role_id'];
                    $tmp['assigned_by'] = $data['emp_id'];
                    $tmp['appid'] = $this->appid;
                    // var_dump($tmp);
                    M('OaUserRole')->add($tmp);
                }
                continue;
            }else{
                if($emp['empower'] == false) {
                    M('OaUserRole')->where(array('id'=>$userRole['id']))->delete();
                }
            }
        }
        echo api_return(0,null);
    }
}
